// @/api/access.ts

import { defineFakeRoute } from "vite-plugin-fake-server/client";
import { faker } from "@faker-js/faker/locale/zh_CN";
import dayjs from "dayjs";
import { ref } from "vue";

// 默认 token 2小时过期
// 这里设置的数值仅用于测试 refreshToken 是否生效，大小无意义
const expired = () => dayjs().add(2, "hour").format("YYYY-MM-DD HH:mm:ss");

const adminUser = ref({
  uid: 1,
  username: "admin",
  nickname: "系统管理员MOCK",
  phone: "13700000000",
  email: "vas-admin@faker.com",
  // 一个用户可能有多个角色
  roles: ["admin"],
  // 按钮级别权限
  permissions: [
    "System",
    "SystemUser",
    "SystemRole",
    "SystemMenu",
    "SystemDept",
    "Template",
    "TemplateTable",
    "TemplateSetting",
    "Testing",
    "TestingComponent",
    "TestingPermission",
    "backend:btn:add",
    "backend:btn:edit",
    "backend:btn:delete",
    "TestingAbout",
    "TestingAdmin"
  ],
  remark: "一个热爱开源的前端工程师"
});

const commonUser = ref({
  uid: 2,
  username: "common",
  nickname: "普通管理员MOCK",
  phone: "",
  email: "",
  roles: ["common"],
  permissions: [
    "Testing",
    "TestingComponent",
    "TestingPermission",
    "TestingCommon",
    "TestingAbout",
    "backend:btn:add",
    "backend:btn:edit"
  ],
  remark: ""
});

// 登录用户信息
// 内置admin和common
export const getUserRef = (headers: any) => {
  if (headers.authorization?.includes("admin")) {
    return adminUser;
  } else {
    return commonUser;
  }
};

const logs: any[] = [];

for (let i = 0; i < 100; i++) {
  logs.push({
    id: i + 1,
    ipAddress: faker.internet.ipv4(),
    ipLocation: "中国口口省" + faker.location.city(),
    userAgent: {
      system: "Windows 10",
      browser: "Chrome 128"
    },
    summary: faker.book.title(), // 详情
    createTime: new Date().setDate(new Date().getDate() - 1)
  });
}

export default defineFakeRoute([
  {
    url: "/access/login",
    method: "post",
    response: ({ body }) => {
      if (body.passport === "admin") {
        return {
          success: true,
          message: "操作成功",
          data: {
            accessToken: "eyJhbGciOiJIUzUxMiJ9.admin",
            refreshToken: "eyJhbGciOiJIUzUxMiJ9.refresh",
            expires: expired()
          }
        };
      } else {
        return {
          success: true,
          message: "操作成功",
          data: {
            accessToken: "eyJhbGciOiJIUzUxMiJ9.common",
            refreshToken: "eyJhbGciOiJIUzUxMiJ9.refresh",
            expires: expired()
          }
        };
      }
    }
  },
  {
    url: "/access/info",
    method: "get",
    response: ({ headers }) => {
      return {
        success: true,
        message: "操作成功",
        data: getUserRef(headers).value
      };
    }
  },
  {
    url: "/access/info",
    method: "put",
    response: ({ headers, body }) => {
      const user = getUserRef(headers);
      user.value.nickname = body.nickname;
      user.value.phone = body.phone;
      user.value.email = body.email;
      user.value.remark = body.remark;
      return {
        success: true,
        message: "操作成功",
        data: user.value
      };
    }
  },
  {
    url: "/access/refresh-token",
    method: "post",
    // 用于测试当刷新失效时的情况
    // statusCode: 401,
    response: ({ body, headers }) => {
      const username = getUserRef(headers).value.username;
      if (body.refreshToken) {
        return {
          success: true,
          message: "操作成功",
          data: {
            accessToken: "eyJhbGciOiJIUzUxMiJ9.new" + username,
            refreshToken: "eyJhbGciOiJIUzUxMiJ9.new" + username + "Refresh",
            expires: expired()
          }
        };
      } else {
        return {
          success: false,
          message: "操作失败！口令不匹配"
        };
      }
    }
  },
  {
    url: "/access/password",
    method: "put",
    response: () => {
      return {
        success: true,
        message: "操作成功"
      };
    }
  },
  // 账户设置-个人安全日志
  {
    url: "/access/logs/page",
    method: "post",
    response: ({ body }) => {
      return {
        success: true,
        message: "操作成功",
        data: {
          list: logs.slice(
            (body.page - 1) * body.pageSize,
            body.page * body.pageSize
          ),
          total: logs.length,
          pageSize: body.pageSize,
          currentPage: body.page
        }
      };
    }
  }
]);
